package com.example.smallmall.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smallmall.common.api.CommonResult;
import com.example.smallmall.dto.AdminLoginParam;
import com.example.smallmall.entity.SpManager;
import com.example.smallmall.service.ISpManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author WSGL
 * @since 2020-07-28
 */
@Api(tags = "登录用户管理")
@RestController
@RequestMapping("/admin")
public class SpManagerController {
    @Resource
    private ISpManagerService iSpManagerService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "登录后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map<String, String>> login(@RequestBody AdminLoginParam adminLoginParam) {
        String token = iSpManagerService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "后台用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<SpManager> register(@RequestBody AdminLoginParam adminLoginParam) {
        SpManager spManager = new SpManager();
        // 获取当前时间
        long time = DateUtil.date().getTime();
        int nowTimeInt = Math.toIntExact((time / 1000));
        spManager.setMgName(adminLoginParam.getUsername());
        spManager.setMgPwd(passwordEncoder.encode(adminLoginParam.getPassword()));
        spManager.setMgTime(nowTimeInt);
        spManager.setMgState(true);
        boolean save = iSpManagerService.save(spManager);
        if (save) {
            return CommonResult.success(spManager);
        } else {
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("根据ID查询后台用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Map<String, Object>> listManagerById(@PathVariable("id") Integer id) {
        LambdaQueryWrapper<SpManager> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SpManager::getMgId, id);
        Map<String, Object> objectMap = iSpManagerService.getMap(lambdaQueryWrapper);
        if (!objectMap.isEmpty()) {
            return CommonResult.success(objectMap);
        } else {
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("编辑更新后台管理用户")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public CommonResult<SpManager> updateManager(@PathVariable("id") Integer id, @RequestBody SpManager spManager) {
        LambdaQueryWrapper<SpManager> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SpManager::getMgId, id);
        boolean update = iSpManagerService.saveOrUpdate(spManager, lambdaQueryWrapper);
        if (update) {
            return CommonResult.success(spManager);
        } else {
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("删除后台用户")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public CommonResult<Boolean> deleteManager(@PathVariable("id") Integer id) {
        boolean remove = iSpManagerService.removeById(id);
        if (remove) {
            return CommonResult.success(true);
        } else {
            return CommonResult.failed("操作失败");
        }
    }
}
